import re

from django_redis import get_redis_connection
from rest_framework import serializers

import logging

from rest_framework_jwt.settings import api_settings

from users.models import User

logger = logging.getLogger('django')

class ImageCodeCheckSerializer(serializers.Serializer):
    """
    图片验证码校验序列化器
    """

    image_code_id = serializers.UUIDField()
    text = serializers.CharField(min_length=4, max_length=4)

    def validate(self, attrs):
        # 校验
        image_code_id = attrs['image_code_id']
        text = attrs['text']

        # 查询真实图片验证码
        redis_conn = get_redis_connection('verify_code')
        image_code_redis = redis_conn.get('img_%s' % image_code_id)
        if not image_code_redis:
            raise serializers.ValidationError('图片验证码无效')

        # 删除图片验证码
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except Exception as e:
            logger.error(e)

        # 比较图片验证码
        image_code_redis = image_code_redis.decode()
        if text.lower() != image_code_redis.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 判断是否在60s内
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            raise serializers.ValidationError("请求次数太频繁")

        return attrs
